import WxValidate from "../../../utils/WxValidate.js";
import tool from "../../../utils/tool.js";
const app = getApp();
var url = app.getURL();

Page({
  data: {
    form:{},
    index:'',
    type:'',
    hidden:true,
    items:[
      {name:'网络',value:'1'},
      {name:'电脑',value:'2'},
      {name:'水类',value:'3'},
      {name:'电类',value:'4'},
      {name:'其他',value:'5'}
    ],
    imgList: [],
    picker: [],
  },
  hideKeyboard:function(e){
    if(e.detail.value.length>=11){
      wx.hideKeyboard()
  }
}, 
// 选择时间
PickerChange(e) {
  this.setData({
    index: e.detail.value
  })
},
// 多选选择类型
  checkboxChange:function(e){
    // console.log('你选中的项目有:'+e.detail.value);
    this.setData({
      type:e.detail.value
    })
 },
 ChooseImage() {
  wx.chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    success: (res) => {
      if (this.data.imgList.length != 0) {
        this.setData({
          imgList: this.data.imgList.concat(res.tempFilePaths)
        })
      } else {
        this.setData({
          imgList: res.tempFilePaths
        })
      }
    }
  });
},
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '',
      content: '确定要删除这张照片吗？',
      cancelText: '再看看',
      confirmText: '确认删除',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },

// 初始化表单验证
onLoad: function () {
  this.isLogin();
  this.initValidate();
let that = this;
  //获取基本信息
  wx.getStorage({
    key: 'allMessage',
    success:function(res){
      that.setData({
        message: res.data,
      })
    }
  })
  
  // 获取预约时间
  wx.request({
    url: url+'/order/app/order/bussi/repair/getOrdTimeRange',
    success:function(res) {
      // console.log(res.data.data)
      that.setData({
        picker:res.data.data
      })
    }
  })
},

//判断是否登录，如果未登录的话就提示登录
isLogin(){
  let that = this;
//获取本地缓存的用户信息
let userName = wx.getStorageSync('cookieNickname')
  if(userName==null||userName==''){
    wx.showToast({
      title: "请先登录",
      icon: "none",
      duration: 2000
      })
      setTimeout(function(){
        wx.switchTab({
          url: '../../my/user/user'
        });
      },600)  
  }
},

// 报错
showModal(error) {
  wx.showModal({
    content: error.msg,
    showCancel: false,
  })
},

initValidate() {
  const rules = {
    name: {
      required: true,
      maxlength: 10
    },
    phone: {
      required: true,
      tel: true
    },
    address:{
      required: true,
    },
    choTime:{
      required: true
    },
    type:{
      required: true
    }
  }

  const message = {
    name: {
      required: '请输入姓名',
      maxlength: '名字不能超过10个字'
    },
    phone: {
      required:'请填写手机号',
      tel:'请填写正确的手机号'
    }, 
    address: {
      required: '请填写宿舍地址'
    },
    choTime: {
      required: '请选择预约的时间',
    }, 
    type: {
      required: '请选择问题类型',
    }
  }
  //实例化当前的验证规则和提示消息
  this.WxValidate = new WxValidate(rules, message);
},
formSubmit: tool.throttle(function (e){
  this.submit(e);
},8000),
submit: function(e) {
  let that = this
  console.log('form发生了submit事件，携带的数据为：', e.detail.value)
  const params = e.detail.value
  let tempFilePaths = this.data.imgList
   
  //校验表单
  if (!this.WxValidate.checkForm(params)) {
    const error = this.WxValidate.errorList[0]
    this.showModal(error)
    return false
  }
    else{
      if(this.data.imgList==''){
        wx.showModal({
          content: '请上传一张图片',
          showCancel: false,
        })
         return false
      }
      // 上传图片
    wx.uploadFile({
      url: url+'/fileUpload',
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {
        'folder': 'userImg' 
      },
      success (res){
        var fi = JSON.parse(res.data)//转为对象使用
        console.log(fi)
        var backImgUrl=fi.data
        // console.log(backImgUrl)
      wx.request({
        url: url+'/order/app/order/bussi/repair/auth/submitRepairBussi',
        method:'POST',
        header: {// 设置请求的 header
          'content-type': 'application/json',
          token:wx.getStorageSync('cookieToken')
        },
        data:{
          "custId":that.data.message.id,
          "address": params.address,
          "name": params.name,
          "phone": params.phone,
          "remark": params.remarks,
          "photoList": [backImgUrl],
          "repairTime": params.choTime,
          "repairType": params.type.toString()
        },
        success(res){
          // 验证通过后执行部分
          let orderNbr = res.data.data.orderNbr
          console.log(orderNbr)
          if(res.data.code==200){
            // 增加延时提交动画
            wx.showToast({
              title: '提交中',
              icon: 'loading',
              duration: 1000
            });
            setTimeout(function(){
              wx.showToast({
                title: '提交成功'
              })
            },1000)
            // 跳转支付
            that.goPay(orderNbr)
          }else{
            wx.showToast({
              title: '提交失败',
              icon: 'error',
              duration: 1000
            });
          }
        },
        fail: function (res) {
          console.log('错误' + ':' + res)
        }
      })
     }
    })
    }
  },

  // 订单支付
  goPay(e){
    let payNbr=e
    wx.request({
      url: url+'/order/app/order/auth/payOrder',
      method: "POST",
      header: {// 设置请求的 header
        'content-type': 'application/json',
        token:wx.getStorageSync('cookieToken')
      },
      data: { order:payNbr },
      success(res) {
        console.log(res)
        if(res.data.code==200){
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1000
          })
          setTimeout(function(){
            wx.switchTab({
                url: '/pages/index/index'
            })  
        },1500)
        }else if(res.data.code==301){
          wx.showToast({
            title: '钱包未开通',
            icon: 'error',
            duration: 1000
          })
          setTimeout(function(){
            wx.redirectTo({
                url: '/pages/my/user/wallet/wallet'
            })  
        },1500)
        }else if(res.data.code==412){
          wx.showToast({
            title: '订单不存在',
            icon: 'error',
            duration: 1000
          })
          setTimeout(function(){
            wx.redirectTo({
                url: '/pages/my/user/wallet/wallet'
            })  
        },1500)
        }else if(res.data.code==413){
          wx.showToast({
            title: '订单支付失败',
            icon: 'error',
            duration: 1000
          })
          setTimeout(function(){
            wx.redirectTo({
                url: '/pages/my/user/wallet/wallet'
            })  
        },1500)
        }else{
          wx.showToast({
            title: '支付失败',
            icon: 'error',
            duration: 1000
          })
          setTimeout(function(){
            wx.redirectTo({
                url: '/pages/my/user/wallet/wallet'
            })  
          },1500)
        }
      }
    })
  },

})
